package com.telit.common.util;

import cn.hutool.core.date.BetweenFormater;
import cn.hutool.core.date.DateUtil;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import org.slf4j.Logger;

import java.util.concurrent.TimeUnit;


/**
 * Create by Chencf  2022/10/29
 */
public class LogUtil {
    private static final Cache<String, Long> localCache = CacheBuilder.newBuilder()
            .expireAfterWrite(1, TimeUnit.DAYS)
            .maximumSize(1000)
            .build();

    /**
     * 定时任务日志打印模板
     */
    // 任务开始时打印
    public static void taskLogBegin(Logger logger,String taskName,String UUID) {
        if (logger == null || !logger.isInfoEnabled())
            return;
        if (UUID != null)
            localCache.put(UUID, System.currentTimeMillis());
        // 任务开始时暂不打印日志，仅在结束时打印一条即可
        // logger.info("{} {}", UUID, taskName);
    }
    // 定时任务未获取分布式锁时
    public static void taskLogUnLock(Logger logger, String taskName, String UUID, String lockKey) {
        if (UUID != null)
            localCache.invalidate(UUID);
        if (logger == null || !logger.isInfoEnabled())
            return;
        logger.warn("warn {} {} 未获取分布式锁，跳过更新 LockKey:{}", UUID, taskName, lockKey);
    }
    // 定时任务结束时
    public static void taskLogEnd(Logger logger,String taskName,String UUID) {
        if (logger == null || !logger.isInfoEnabled())
            return;

        String useTime = "unknown";
        if (UUID != null) {
            Long startTime = localCache.getIfPresent(UUID);
            if (startTime != null) {
                useTime = DateUtil.formatBetween(System.currentTimeMillis() - startTime, BetweenFormater.Level.MILLSECOND);
                localCache.invalidate(UUID);
            }
        }
        logger.info("{} {} 共耗时：{}", UUID, taskName, useTime);
    }
}
